<template>
  <div class="app-container">
    <div class="left baseBoderShadow bgWhite baseBorderRadius">
      <div class="seachBox">
        <el-input v-model.trim="seachName_jg" placeholder="请输入机构名称" clearable @keyup.enter.native="search_jg">
          <i slot="suffix" class="el-icon-search" style="line-height: 36px; width: 30px;cursor: pointer;" @click="search_jg" />
        </el-input>
      </div>
      <div id="greenTree" class="scroBox" style=" height: 624px;">
        <el-scrollbar :wrap-style="[{ 'height': '100%' }]">
          <el-tree ref="tree" :data="treeDate" :default-expanded-keys="keysArr" :current-node-key="currentNodekey" :props="defaultProps" node-key="id" highlight-current @node-click="zzjgNodeClick">
            <template slot-scope="{ node, data }">
              <span :title="data.zzjg_name" class="overSpan">{{ data.zzjg_name }}</span>
            </template>
          </el-tree>
        </el-scrollbar>
      </div>
    </div>
    <div class="right">
      <!-- 查询和其他操作 -->
      <div class=" filter-container">
        <el-input v-model="listQuery.title" clearable class="filter-item" style="width: 200px;" placeholder="输入商品名称" />
        <el-input v-model="listQuery.barcode" clearable class="filter-item" style="width: 200px;" placeholder="输入商品条形码" />
        <el-select v-model="listQuery.status" clearable style="width: 200px" class="filter-item" placeholder="选择商品状态">
          <el-option v-for="(item,index) in goodsStatusMap" :key="index" :label="item.name" :value="item.value" />
        </el-select>
        <el-cascader :props="{label:'title', value:'id', children:'childrenList', checkStrictly: true}" :options="categoryOptions" placeholder="请选择类目" clearable class="filter-item" filterable style="width: 200px;" @change="handleCategoryOption" />
        <el-button v-permission="['product:product:list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
        <el-button v-permission="['product:product:create']" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
        <el-button v-permission="['product:product:batchdelete']" :disabled="selectedIds.length === 0" class="filter-item" type="danger" icon="el-icon-delete" @click="handleBatchDelete">批量删除</el-button>
      </div>

      <!-- 查询结果 -->
      <el-table
        v-loading="listLoading"
        height="680px"
        :data="list"
        size="small"
        element-loading-text="正在查询中。。。"
        border
        fit
        highlight-current-row
        @selection-change="handleSelectionChange"
      >

        <el-table-column align="center" type="selection" width="55" />
        <el-table-column
          type="index"
          label="序号"
          width="50"
        />
        <el-table-column align="center" width="200px" label="商品ID" prop="id" />

        <el-table-column align="center" min-width="100" label="名称" prop="name" />


        <el-table-column align="center" label="详情" prop="detail" width="90">
          <template slot-scope="scope">
            <el-dialog :visible.sync="detailDialogVisible" title="商品详情">
              <div v-html="goodsDetail" />
            </el-dialog>
            <el-button type="primary" size="mini" @click="showDetail(scope.row)">查看</el-button>
          </template>
        </el-table-column>


        <el-table-column align="center" label="排序" prop="orderC" />




        <el-table-column
          show-overflow-tooltip
          align="left"
          max-width="300"
          min-width="300"
          label="描述"
          prop="description"
        />

        <el-table-column align="center" fixed="right" label="操作" width="320" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button v-permission="['product:product:edit']" type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button v-permission="['product:product:delete']" type="danger" style="margin:5px" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </div>
    <el-tooltip placement="top" content="返回顶部">
      <back-to-top :visibility-height="100" />
    </el-tooltip>

    <!-- 设置规则详细信息 -->
    <el-dialog
      title="规则详情"
      :visible.sync="dialogParameterDetail"
      width="600px"
    >
      <div>
        <div>
          <el-button
            type="primary"
            @click="addParameterDetail"
          >添 加</el-button>
        </div>
        <el-table
          :data="parameterDetail"
          border
        >
          <el-table-column
            label="序号"
            align="center"
            width="60px"
          >
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="名称">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.name"
                v-blurTrim
                placeholder="请输入"
              />
            </template>
          </el-table-column>
          <el-table-column label="价格">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.price"
                v-blurTrim
                type="number"
                placeholder="请输入"
              />
            </template>
          </el-table-column>
          <el-table-column label="是否星标">
            <template slot-scope="scope">
              <div class="special_switch_wrap">
                <el-switch
                  v-model="scope.row.isStar"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-text="是"
                  inactive-text="否"
                  :active-value="1"
                  :inactive-value="0"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="150px"
          >
            <template slot-scope="scope">
              <el-button
                type="warning"
                size="mini"
                round
                @click="deleteParameterDetailFunc(scope.$index)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="dialog-footer">
        <el-button
          type="primary"
          @click="parameterDetailSureFunc"
        >确 定</el-button>
        <el-button @click="dialogParameterDetail = false">取消</el-button>
      </div>
    </el-dialog>
    <!-- 设置规格互斥信息 -->
    <el-dialog
      :visible.sync="dialogParameter"
      title="规格互斥设置"
      width="800px"
    >
      <div class="parameter-wrap">
        <div class="parameter-left parameter-item">
          <el-tree
            ref="tree"
            :data="parameterData"
            default-expand-all
            node-key="id"
            highlight-current
            :props="defaultProps"
            @node-click="nodeClick"
          />
        </div>
        <div class="parameter-right parameter-item">
          <el-checkbox-group
            v-if="showTree"
            v-model="checkList"
            @change="changeCheckFunc"
          >
            <el-tree
              ref="tree"
              :data="parameterData"
              default-expand-all
              node-key="id"
              :props="defaultProps"
            >
              <template slot-scope="{ node, data }">
                <div v-if="node.level > 1">
                  <el-checkbox :label="data.id">{{ data.name }}</el-checkbox>
                </div>
                <div v-else>
                  {{ node.level }}
                  <span>{{ data.name }}</span>
                </div>
              </template>
            </el-tree>
          </el-checkbox-group>
        </div>
      </div>
      <div style="text-align: center;padding-top: 20px;">
        <el-button
          type="primary"
          @click="saveParameterExclude"
        >保存</el-button>
      </div>
    </el-dialog>
    <!-- 维护规格 -->
    <el-dialog
      :visible.sync="dialogParameterSetting"
      title="商品规格维护"
      width="800px"
    >
      <div style="padding-bottom: 10px;">
        <el-button
          type="primary"
          size="mini"
          round
          @click="addNewParameterFunc"
        >新增标签</el-button>
      </div>
      <el-table
        :data="coldProductParameter"
        border
      >
        <el-table-column
          label="序号"
          align="center"
          width="60px"
        >
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="规则名称">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.title"
              v-blurTrim
              placeholder="请输入"
            />
          </template>
        </el-table-column>
        <el-table-column label="价格">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.price"
              v-blurTrim
              type="number"
              placeholder="请输入"
            />
          </template>
        </el-table-column>
        <el-table-column label="是否星标">
          <template slot-scope="scope">
            <div class="special_switch_wrap">
              <el-switch
                v-model="scope.row.isStar"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="规格详细设置">
          <template slot-scope="scope">
            <el-link
              type="primary"
              @click="setParameterDetail(scope.$index)"
            >设置</el-link>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="150px"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              round
              @click="addNewParameterFunc"
            >新增</el-button>
            <el-button
              type="warning"
              size="mini"
              round
              @click="deleteParameterFunc(scope.$index)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="padding-top: 20px;text-align: center;">
        <el-button type="primary" @click="saveParameter">保 存</el-button>
        <el-button @click="dialogParameterSetting = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listProduct, deleteProduct, detailProduct, freezeOrActivtion, batchDeleteProduct, selectById } from "@/api/groupshopad";
import BackToTop from "@/components/BackToTop";
import { categoryTree } from "@/api/category";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import {
  saveParameterRule,
  // saveParameter,
  updateParameterById
} from "@/api/product/product.js";
export default {
  name: "ProductList",
  components: { BackToTop, Pagination },
  data() {
    return {
      userZzjg: [],
      defaultProps: {
        label: "zzjg_name",
        value: "id",
        children: "children"
      },
      currentNodekey: "",
      keysArr: [],
      treeDate: [],
      currentId: "",
      seachName_jg: "",
      isBaiHuo: 0,
      // 迁移过来的逻辑
      editId: null,
      dialogParameterDetail: false,
      parameterDetail: [],
      parameterIndex: null,
      defaultProps: {
        label: "name"
      },
      dialogParameter: false,
      checkList: [],
      showTree: false,
      excludeIdsObj: {},
      detailId: null,
      // 某个商品规格信息
      coldProductParameter: [],
      // 规格设置信息
      dialogParameterSetting: false,
      // <<<<<<<
      list: [],
      total: 0,
      listLoading: true,
      categoryOptions: [],
      goodsStatusMap: [{ value: 0, name: "下架" }, { value: 1, name: "正常" }],
      listQuery: {
        page: 1,
        limit: 20,
        title: undefined,
        status: undefined,
        barcode: undefined,
        categoryId: undefined
      },
      goodsDetail: "",
      detailDialogVisible: false,
      selectedIds: []
    };
  },
  created() {
    // this.getList();

  },
  mounted() {
    this.getCurrentUserZzjgs();
    this.getDepartmentList();
  },
  methods: {
    resetData() {
      this.listQuery = {
        page: 1,
        limit: 20,
        title: undefined,
        status: undefined,
        barcode: undefined,
        categoryId: undefined
      };
      // this.tableData = [];
      // this.currentPage = 1;
      // this.pageSize = 10;
      // this.totalPage = 0;
      // this.checkAll = false;
      // this.isIndeterminate = false;
      // this.checkList = [];
      // this.allcheckbox = [];
    },
    async getCurrentUserZzjgs() {
      this.userZzjg = [];
      const res = await this.$store.dispatch("qxgl-yhzzgl/getCurrentUserZzjgs");
      this.userZzjg = [1];
      res.data.map(item => {
        this.userZzjg = [];
        this.userZzjg = [...this.userZzjg, item.zzjgId - 0];
      });
    },
    /**
     * @name zzjgnodeClick
     * @description 点击树形结构
     * @author wqy
     * @date 2019-10-31 10:32:34
     */
    zzjgNodeClick(data, currentNode, node) {
      this.currentId = data.id;
      this.currentName = data.zzjg_name;
      this.parentId = data.parent_id;

      this.isEmpty = false; // 全局搜索，输入框当前是否为空
      this.byJgFlag = true; // 当前为组织机构的获取的列表
      // 清空多选框
      this.seachName = "";
      this.resetData();
      this.getList();// 根据组织机构查询用户
      this.refreshCategoryOptions();
    },
    /**
     * @name getDepartmentList
     * @description 获取第一级别的树形结构
     * @author wqy
     * @date 2019-10-31 10:10:24
     */
    async getDepartmentList() {
      const data = {
        searchName: this.seachName_jg
      };
      const res = await this.$store.dispatch(
        "qxgl-yhzzgl/getDepartmentList",
        data
      );
      this.treeDate = res.data;
      const id = res.data[0].id;
      this.currentName = res.data[0].zzjg_name;
      this.currentId = id;
      this.firstId = id; // 记录最高级别的id
      // 设置默认选中并高亮显示
      if (this.userZzjg.length !== 0) {
        this.keysArr = this.userZzjg;
        this.currentId = this.userZzjg[0];
        this.currentNodekey = this.userZzjg[0];
      } else {
        this.currentNodekey = id;
        this.keysArr.push(id);
      }
      this.$nextTick(() => {
        const tree = this.$refs.tree;
        tree.setCurrentKey(this.currentId); // 指定选中的节点
        // getCurrentNode 获取当前节点的信息
        const currentNode = this.$refs.tree.getCurrentNode();
        this.currentName = currentNode.zzjg_name;
        this.parentId = currentNode.parent_id;
        // 根据组织机构查询用户
        this.getList();
        this.refreshCategoryOptions();
      });
    },
    /**
     * @name search_jg
     * @description 搜索机构
     * @author wqy
     * @date 2019-10-31 10:20:21
     */
    async search_jg() {
      const data = {
        searchName: this.seachName_jg
      };
      const res = await this.$store.dispatch(
        "qxgl-yhzzgl/getDepartmentList",
        data
      );
      this.treeDate = res.data;
      // 清空右侧
      // this.checkAll = false;
      // this.isIndeterminate = false;
      this.checkList = [];
      // this.currentPage = 1;
    },
    /**
     * @name addNewParameterFunc
     * @description 添加新的规则
     * @param {}
     * @author cjs
     * @date 2021-07-17 14:41:49
     */
    addNewParameterFunc() {
      this.coldProductParameter.push({
        title: "",
        price: "",
        isStar: 0,
        coldProductParameterDetail: [
          // { name: "", isStar: 0, price: "",excludeIds: "" }
        ]
      });
    },
    /**
     * @name deleteParameterFunc
     * @description 删除规则
     * @param {}
     * @author cjs
     * @date 2021-07-17 14:51:10
     */
    deleteParameterFunc(index) {
      this.coldProductParameter.splice(index, 1);
    },
    /**
     * @name saveParameter
     * @description 保存规格
     * @param {}
     * @author cjs
     * @date 2021-07-31 11:21:37
     */
    async saveParameter() {
      // updateParameterById
      const { coldProductParameter, editId: productId } = this;
      const param = {
        productId,
        coldProductParameter,
        zzjgId: this.currentId
      };
      await updateParameterById(param);
      this.$message({
        message: "保存成功",
        type: "success"
      });
      this.dialogParameterSetting = false;
    },
    /**
     * @name handleCommand
     * @description 规格
     * @param {}
     * @author cjs
     * @date 2021-07-31 11:12:00
     */
    handleCommand(row, val) {
      if (val === "a") {
        this.editParameter(row);
      } else {
        this.parameterSetting(row);
      }
    },
    /**
     * @name editParameter
     * @description 设置规格
     * @param {}
     * @author cjs
     * @date 2021-07-31 11:13:45
     */
    async editParameter(row) {
      this.editId = row.id;
      this.coldProductParameter = [];
      const res = await selectById({
        spuId: row.id,
        isBaiHuo: this.isBaiHuo
      });
      const data = res.data.data.coldProductParameter || [];
      this.coldProductParameter = data.map(item => {
        return {
          ...item,
          coldProductParameterDetail: item.coldProductParameterDetail || []
        };
      });
      this.dialogParameterSetting = true;
    },
    async saveParameterExclude() {
      // saveParameterRule
      const list = [];
      for (const key in this.excludeIdsObj) {
        list.push({
          parameterDetailId: key,
          excludeIds: this.excludeIdsObj[key].join(",")
        });
      }
      await saveParameterRule(list);
      this.$message({
        type: "success",
        message: "规则设置成功"
      });
    },
    changeCheckFunc(val) {
      this.excludeIdsObj[this.detailId] = [...val];
    },
    nodeClick(data, node) {
      if (node.level === 1) {
        this.showTree = false;
        return;
      }
      this.showTree = true;
      this.checkList = [...(this.excludeIdsObj[data.id] || [])];
      this.detailId = data.id;
    },
    async parameterSetting(row) {
      this.editId = row.id;
      this.excludeIdsObj = {};
      const res = await selectById({
        spuId: row.id,
        isBaiHuo: this.isBaiHuo
      });
      const data = res.data.data.coldProductParameter || [];
      const list = [];
      data.map(item => {
        const children = item.coldProductParameterDetail || [];
        children.map(vo => {
          this.excludeIdsObj[vo.id] = vo.excludeIds
            ? vo.excludeIds.split(",")
            : [];
        });
        list.push({
          id: String(item.id),
          name: item.title,
          children: children.map(vo => {
            // console.log(vo)
            // vo.id = String(vo.id);
            return {
              id: String(vo.id),
              name: vo.name
            };
          })
        });
      });

      this.parameterData = list;
      this.showTree = false;
      this.dialogParameter = true;
    },
    /**
     * @name parameterDetailSureFunc
     * @description 设置规则详细信息确定方法
     * @param {}
     * @author cjs
     * @date 2021-07-17 15:48:45
     */
    parameterDetailSureFunc() {
      this.coldProductParameter[
        this.parameterIndex
        ].coldProductParameterDetail = this.parameterDetail;
      this.dialogParameterDetail = false;
    },
    /**
     * @name addParameterDetail
     * @description 添加规格详情
     * @param {}
     * @author cjs
     * @date 2021-07-17 15:45:54
     */
    addParameterDetail() {
      this.parameterDetail.push({
        name: "",
        isStar: 0,
        price: "",
        excludeIds: ""
      });
    },
    /**
     * @name deleteParameterDetailFunc
     * @description 删除规格详情
     * @param {}
     * @author cjs
     * @date 2021-07-17 15:46:38
     */
    deleteParameterDetailFunc(index) {
      this.parameterDetail.splice(index, 1);
    },
    /**
     * @name setParameterDetail
     * @description 设置规则详细信息
     * @param {}
     * @author cjs
     * @date 2021-07-17 15:40:32
     */
    setParameterDetail(index) {
      this.parameterIndex = index;
      this.parameterDetail = JSON.parse(
        JSON.stringify(
          this.coldProductParameter[index].coldProductParameterDetail
        )
      );
      this.dialogParameterDetail = true;
    },
    getList() {
      this.listLoading = true;
      this.listQuery.zzjgId = this.currentId;// 设置查询的组织机构ID
      listProduct(this.listQuery)
        .then(response => {
          response.data.data.items.forEach(item => {
            item.price = item.price / 100;
            item.originalPrice = item.originalPrice / 100;
            item.vipPrice = item.vipPrice / 100;
          });
          this.list = response.data.data.items;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleCreate() {
      this.$router.push({ path: "/groupshop/add", query: { zzjgId: this.currentId }});
    },
    handleUpdate(row) {
      this.$router.push({ path: "/groupshop/add", query: { id: row.id, zzjgId: this.currentId }});
    },
    showDetail(row) {
      console.log(row)
      if (!this.detailDialogVisible) {
        detailProduct(row.id)
          .then(response => {
            this.goodsDetail = response.data.data.description.replace(/<img/g, "<img style='max-width:100%;height:auto;line-height:0px'");
            this.detailDialogVisible = true;
          });
      }
    },
    handleDelete(row) {
      this.$confirm("此操作将永久删除商品--" + row.title + "--, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteProduct(row.id)
          .then(response => {
            this.$notify.success({
              title: "成功",
              message: "删除成功"
            });
            const index = this.list.indexOf(row);
            this.list.splice(index, 1);
          })
          .catch(response => {
            this.$notify.error({
              title: "失败",
              message: response.data.errmsg
            });
          });
      }).catch(() => {
        return false;
      });
    },
    refreshCategoryOptions() {
      this.categoryOptions = [];
      if (this.categoryOptions.length === 0) {
        categoryTree(this.currentId).then(response => {
          this.categoryOptions = response.data.data;
        });
      }
    },
    handleCategoryOption(e) {
      if (e !== undefined) {
        const tag = e[e.length - 1];
        this.listQuery.categoryId = tag; // 回调指定分类
      } else {
        this.listQuery.categoryId = undefined;
      }
    },
    freezeOrActivationBtn(row, title) {
      var status = 0;
      var sign = "";
      if (title === "activation") {
        status = 1;
        sign = "激活";
      } else if (title === "freeze") {
        status = 0;
        sign = "冻结";
      } else {
        return false;
      }

      this.$confirm("此操作将" + sign + "商品--" + row.title + "--, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(() => {
        return false;
      }).then(() => {
        freezeOrActivtion(row.id, status).then(response => {
          this.$notify.success({
            title: "成功",
            message: sign + "成功"
          });
          const index = this.list.indexOf(row);
          this.list.splice(index, 1, response.data.data);
        }).catch(response => {
          this.$notify.error({
            title: "失败",
            message: response.data.errmsg
          });
        });
      });
    },
    handleSelectionChange(e) {
      const temp = [];
      e.forEach(item => {
        temp.push(item.id);
      });
      this.selectedIds = temp;
    },
    handleBatchDelete(e) {
      // 执行批量删除
      this.$confirm("此操作将永久删除选中的" + this.selectedIds.length + "件商品, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        batchDeleteProduct(this.selectedIds)
          .then(response => {
            this.$notify.success({
              title: "成功",
              message: "删除成功"
            });
            this.getList();
          })
          .catch(response => {
            this.$notify.error({
              title: "失败",
              message: response.data.errmsg
            });
          });
      }).catch(() => {
        return false;
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.parameter-wrap {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .parameter-item {
    width: 48%;
    height: 400px;
    border: 1px solid #e0e0e0;
    padding: 10px;
    overflow-y: auto;
  }
}

</style>
